<template>
  <div>

    <el-card class="box-card  custom-card">
      <div class="info-section">
        <h3 style="font-size: 18px;font-weight: bold;color: #ffffff;background-color: #409EFF;display: inline-block;
                           padding: 5px 10px;margin-bottom: 10px;border-radius: 4px;">客户信息</h3>
        <div class="info-row">
          <div class="info-item">销售员编号：
            <span><el-input v-model="orderAppliaction.saleCode" placeholder='' style="width: 180px; margin-left: 10px;"
                :disabled="true"></el-input></span>

          </div>
          <div class="info-item">销售员姓名：
            <el-select v-model="orderAppliaction.saleName" placeholder="请选择" style="width: 180px;margin-left: 20px;"
              @change="handleSaleChange">
              <el-option v-for="sale in saleList" :key="sale.code" :label="sale.realName" :value="sale.realName">
              </el-option>
            </el-select>
          </div>
          <div class="info-item"></div> <!-- 空白占位符 -->
        </div>

      </div>
      <div class="info-section">
        <div class="info-row">
          <div class="info-item">申请时间：
            <el-date-picker v-model="orderAppliaction.applicationDate" type="date" placeholder="选择日期"
              style="width: 180px;margin-left: 35px;">
            </el-date-picker>
          </div>
          <div class="info-item">申 请 理 由：
            <span><el-input v-model="orderAppliaction.applicationReason" placeholder=''
                style="width: 180px; margin-left: 10px;"></el-input></span>
          </div>
          <div class="info-item"></div> <!-- 空白占位符 -->
        </div>
      </div>

      <div class="info-section">
        <div class="info-row">
          <div class="info-item">客户编号：
            <span><el-input v-model="orderAppliaction.customerCode" placeholder=''
                style="width: 180px; margin-left: 25px;" :disabled="true"></el-input></span>
          </div>
          <div class="info-item">客户名称：
            <span><el-select v-model="orderAppliaction.customerName" @change="handleCustomerChange" filterable
                placeholder="请选择" style="width: 180px; margin-left: 25px;">
                <el-option v-for="customer in customerList" :key="customer.code" :label="customer.customerName"
                  :value="customer.customerName">
                </el-option>
              </el-select></span>
          </div>
          <div class="info-item">客户公司名称：
            <span><el-input v-model="orderAppliaction.companyName" placeholder=''
                style="width: 180px; margin-left: -5px;" :disabled="true"></el-input></span>
          </div>
        </div>
      </div>

      <div class="info-section">
        <div class="info-row">
          <div class="info-item">客户类别：
            <span><el-input v-model="orderAppliaction.customerCategory" placeholder=''
                style="width: 180px; margin-left: 25px;" :disabled="true"></el-input></span>
          </div>
          <div class="info-item">联系人：
            <span><el-input v-model="orderAppliaction.contactPerson" placeholder=''
                style="width: 180px; margin-left: 40px;" :disabled="true"></el-input></span>
          </div>
          <div class="info-item">公司电话：
            <span><el-input v-model="orderAppliaction.contactPhone" placeholder=''
                style="width: 180px; margin-left: 25px;" :disabled="true"></el-input></span>
          </div>
        </div>
      </div>

      <div class="info-section">
        <div class="info-row">
          <div class="info-item">公司地址:
            <span><el-input v-model="orderAppliaction.companyAddress" placeholder=''
                style="width: 180px; margin-left: 35px;" :disabled="true"></el-input></span>
          </div>
          <div class="info-item">收货地址:
            <span><el-input v-model="orderAppliaction.deliveryAddress" placeholder=''
                style="width: 180px; margin-left: 35px;" :disabled="true"></el-input></span>
          </div>
          <div class="info-item"></div> <!-- 空白占位符 -->
        </div>
      </div>
    </el-card>


    <!-- 订单信息区域 -->
    <el-card class="box-card custom-card">
      <div class="info-section">
        <h3 style="font-size: 18px;font-weight: bold;color: #ffffff;background-color: #13d941;display: inline-block;
                           padding: 5px 10px;margin-bottom: 10px;border-radius: 4px;">订单信息</h3>
        <div class="info-row">
          <div class="info-item">订单申请编号：
            <span><el-input v-model="orderAppliaction.code" placeholder='' style="width: 180px; margin-left: 0px;"
                :disabled="true"></el-input></span>
          </div>
          <div class="info-item">付款方式：
            <span><el-select filterable placeholder="请选择" style="width: 180px; margin-left: 10px;"
                v-model="orderAppliaction.payment">
                <el-option v-for="payment in payments" :key="payment.value" :label="payment.label"
                  :value="payment.value">
                </el-option>
              </el-select></span>
          </div>
          <div class="info-item"></div> <!-- 空白占位符 -->
        </div>
      </div>
      <div class="info-section">
        <div class="info-row">
          <div class="info-item">是否免付定金:
            <span><el-select filterable placeholder="请选择" style="width: 180px; margin-left: 10px;"
                v-model="orderAppliaction.deposit" :disabled="isDepositDisabled">
                <el-option v-for="deposit in deposits" :key="deposit.value" :label="deposit.label"
                  :value="deposit.value">
                </el-option>
              </el-select></span>
          </div>
          <div class="info-item">定金金额：
            <span><el-input v-model="orderAppliaction.depositAmount" :disabled="isDepositDisabled" placeholder=''
                style="width: 180px; margin-left: 10px;"></el-input></span>
          </div>
          <div class="info-item"></div> <!-- 空白占位符 -->
        </div>
      </div>
      <div class="info-section">
        <div class="info-row">
          <div class="info-item">订单种类:
            <span><el-select filterable placeholder="请选择" style="width: 180px; margin-left: 40px;"
                v-model="orderAppliaction.orderType">
                <el-option v-for="orderType in orderTypes" :key="orderType.value" :label="orderType.label"
                  :value="orderType.value">
                </el-option>
              </el-select></span>
          </div>
          <div class="info-item">特价折扣：
            <span><el-input v-model="orderAppliaction.discount" :disabled="isDiscountDisabled" placeholder='范围0-1'
                style="width: 180px; margin-left: 10px;" @input="validateDiscount"></el-input></span>
          </div>
          <div class="info-item"></div> <!-- 空白占位符 -->
        </div>
      </div>
    </el-card>


    <!-- 产品信息区域 -->
    <el-card class="box-card custom-card">
      <div class="info-section">
        <h3 style="font-size: 18px;font-weight: bold;color: #ffffff;background-color: #13d941;display: inline-block;
                           padding: 5px 10px;margin-bottom: 10px;border-radius: 4px;">产品信息</h3>
        <div>
          <el-button plain @click="queryProductVisible = true" :disabled=yesOrNo>添加</el-button>
          <el-table :data="tableData" style="width: 100%" border>
            <el-table-column prop="productName" label="产品名称"></el-table-column>
            <el-table-column prop="productStock" label="库存"></el-table-column>
            <el-table-column prop="count" label="数量">
              <template slot-scope="scope">
                <el-input v-model="scope.row.count" placeholder='' style="width: 180px; margin-left: 10px;"
                  @change="handleCountChange(scope.row)" :disabled=yesOrNo></el-input>
              </template>
            </el-table-column>
            <el-table-column prop="productDescription" label="产品描述"></el-table-column>
            <el-table-column prop="productPrice" label="产品价格"></el-table-column>
            <el-table-column label="操作" width="180">
              <template slot-scope="scope">
                <el-button type="text" size="medium" @click="handleDelete(scope.$index, scope.row)">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </div>
      </div>
      <div class="info-section">
        <el-button type="success" @click="makeSure">确认产品信息</el-button>
      </div>
    </el-card>

    <div class="button-group fixed-buttons-horizontal">
      <el-button @click="refresh">取消</el-button>
      <el-button type="primary" @click="makePrice">发送审批</el-button>
    </div>


    <!--        //查询产品弹框开始----------------------------------------------------------------------------------------------------->
    <el-dialog title="产品列表" :visible.sync="queryProductVisible" width="70%">
      <el-button type="primary" @click="addProduct">添加</el-button>
      <el-table :data="productList" style="width: 100%; margin-top: 20px;" @selection-change="handleSelectionChange">

        <el-table-column type="selection" width="55"></el-table-column>
        <el-table-column prop="productCode" label="产品code"> </el-table-column>
        <el-table-column prop="productName" label="产品名称"></el-table-column>
        <el-table-column prop="productMaterial" label="产品物料" width="180"></el-table-column>
        <el-table-column prop="productDescription" label="产品描述"></el-table-column>
        <el-table-column prop="productStock" label="库存"></el-table-column>
        <el-table-column prop="productPrice" label="价格"></el-table-column>

      </el-table>
    </el-dialog>
    <!--        //查询产品弹框结束----------------------------------------------------------------------------------------------------->

    <!--        //发送审批确认弹框开始----------------------------------------------------------------------------------------------------->
    <el-dialog title="确认页面" :visible.sync="sendVisible" width="70%">
      <div class="confirm-dialog">
        <div class="confirm-item">
          <span class="label">订单申请编号：</span>
          <span class="value">{{ orderAppliaction.code }}</span>
        </div>
        <div class="confirm-item">
          <span class="label">订单金额：</span>
          <span class="value price">¥ {{ orderAppliaction.orderPrice }}</span>
        </div>
        <div class="confirm-item">
          <span class="label">税额：</span>
          <span class="value price">¥ {{ orderAppliaction.tax }}</span>
        </div>
        <div class="confirm-item">
          <span class="label">选择审批人：</span>
          <el-select v-model="orderAppliaction.approver" placeholder="请选择" style="width: 180px;margin-left: 20px;"
              @change="handleSaleChange">
              <el-option v-for="sale in jingLiList" :key="sale.code" :label="sale.realName" :value="sale.code">
              </el-option>
            </el-select>
        </div>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button @click="sendVisible = false">取 消</el-button>
        <el-button type="primary" @click="addOrderApplication">确认发送审批</el-button>
      </div>
    </el-dialog>
    <!--        //发送审批确认弹框结束----------------------------------------------------------------------------------------------------->

  </div>
</template>

<script>
export default {
  data() {
    return {

      pageNum: 1,
      pageSize: 10,
      param: null,
      yesOrNo: false,
      isDepositDisabled: false, // 新增控制定金字段状态的变量
      isDiscountDisabled: false, // 新增控制特价折扣字段状态的变量
      orderAppliaction: {},//订单申请对象
      tableData: [],//申请页面已添加的产品列表
      customerList: [],//客户下拉框数据列表
      productList: [], //查询全部产品列表
      saleList: [],//销售员下拉框数据列表
      jingLiList: [],//经理下拉框数据列表
      multipleSelection: [],//查询产品列表多选
      queryProductVisible: false,//控制查询产品弹框
      sendVisible: false,//控制发送审批确认弹框
      payments: [{ value: '0', label: '先发货后付款' }, { value: '1', label: '先付款后发货' }],
      deposits: [{ value: '0', label: '是' }, { value: '1', label: '否' }],
      orderTypes: [{ value: '0', label: '正常订单' }, { value: '1', label: '特价订单' }],
    }
  },

  methods: {
    refresh() {
      window.location.reload();
    },
    queryAllSale() {
      const roleId = 4;
      this.$axios.get("/api/order-server/uums/queryAllSale/" + roleId)
        .then(resp => {
          console.log(resp.data)
          if (resp.data.code == 200) {
            this.saleList = resp.data.data
          }
        })
    },
    queryAllJingLi() {
      const roleId = 2;
      this.$axios.get("/api/order-server/uums/queryAllSale/" + roleId)
        .then(resp => {
          console.log(resp.data)
          if (resp.data.code == 200) {
            this.jingLiList = resp.data.data
          }
        })
    },
    handleSaleChange(value) {


      const selectedSale = this.saleList.find(sale => sale.realName === value);
      console.log(selectedSale + '---')
      if (selectedSale) {
        this.orderAppliaction.saleCode = selectedSale.code;
      }
    },
    queryAllCustomer() {
      this.$axios.post("/api/order-server/zsbOrder/queryAllCustomer", {})
        .then(resp => {
          console.log(resp.data)
          if (resp.data.code == 200) {
            this.customerList = resp.data.data
          }
        })
    },
    handleCustomerChange(value) {
      const selectedCustomer = this.customerList.find(customer => customer.customerName === value);
      console.log(selectedCustomer + '---')
      if (selectedCustomer) {
        this.orderAppliaction.customerCode = selectedCustomer.code
        this.orderAppliaction.companyName = selectedCustomer.companyName
        this.orderAppliaction.customerCategory = selectedCustomer.customerCategory
        this.orderAppliaction.contactPerson = selectedCustomer.contactPerson
        this.orderAppliaction.contactPhone = selectedCustomer.contactPhone
        this.orderAppliaction.companyAddress = selectedCustomer.companyAddress
        this.orderAppliaction.deliveryAddress = selectedCustomer.deliveryAddress

      }
    },
    createSnowId() {
      this.$axios.post("/api/order-server/zsbOrder/createSnowId", {})
        .then(resp => {

          console.log(resp.data)
          if (resp.data.code == 200) {
            this.orderAppliaction.code = resp.data.data

            console.log(this.orderAppliaction.code);
          }
        })
    },
    queryAllProduct() {
      this.$axios.post("/api/order-server/zsbOrder/queryAllProduct")
        .then(resp => {
          console.log(resp.data)
          if (resp.data.code == 200) {
            this.productList = resp.data.data

            // 遍历产品列表，将每个对象的 count 属性设置为0
            // this.productList.forEach(product => {
            //   product.count = 0;
            // });
          }
        })
    },
    handleCountChange(row) {
      // 当数量变化时，可以在这里处理相关逻辑，例如更新总数量等
      if (row.count > row.productStock) {
        this.$message.warning('数量不能超过库存数量！');
        row.count = row.productStock;
      }
    },
    handleSelectionChange(val) {//点击批量删除复选框调用此方法
      this.multipleSelection = val

    },
    addProduct() {
      this.tableData = this.multipleSelection
      this.queryProductVisible = false
      this.multipleSelection = []
    },
    handleDelete(index, row) {
      this.tableData.splice(index, 1);
      this.$message({
        type: 'success',
        message: '删除成功'
      });
    },
    makeSure() {
      this.$confirm('是否确认产品信息', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {

        //点击确定再发送请求
        this.yesOrNo = true
        let payload = {};
        payload.tableData = this.tableData,
          payload.orderCode = this.orderAppliaction.code

        this.$axios.post("/api/order-server/zsbOrder/addProduct", payload)
          .then(resp => {
            console.log(resp.data)
            if (resp.data.code == 200) {
              this.$message.success('产品信息确认成功！');
            }
          })

      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消操作'
        });
      });

    },
    validateDiscount(value) {
      // 如果输入为空，直接返回
      if (!value) return;

      // 转换为数字
      let num = parseFloat(value);

      // 验证是否为有效数字且在0-1范围内
      if (isNaN(num) || num < 0 || num > 1) {
        this.$message({
          message: '特价折扣必须在0-1之间',
          type: 'warning'
        });
        // 清空无效输入或将值限制在有效范围内
        if (num < 0) {
          this.orderAppliaction.discount = '0';
        } else if (num > 1) {
          this.orderAppliaction.discount = '1';
        } else {
          this.orderAppliaction.discount = '';
        }
      }
    },
    makePrice() {
      if (!this.tableData || this.tableData.length === 0) {
        this.$message.warning('请确认产品信息！');
        return; // 添加return确保后续代码不会执行
      }
      this.$axios.get("/api/order-server/zsbOrder/getOrderPrice/" + this.orderAppliaction.code)
        .then(resp => {
          console.log(resp.data)
          if (resp.data.code == 200) {
            this.orderAppliaction.orderPrice = resp.data.data.orderPrice
            this.orderAppliaction.tax = resp.data.data.tax
            this.sendVisible = true
          }
        })



    },
    addOrderApplication() {
      if(this.orderAppliaction.payment == 1){
        this.orderAppliaction.deposit = 0
        this.orderAppliaction.depositAmount = 0
      }
      this.$axios.post("/api/order-server/zsbOrder/addOrderApplication", this.orderAppliaction)
        .then(resp => {
          console.log(resp.data)
          if (resp.data.code == 200) {
            this.$message.success('订单申请发送成功！');
            this.refresh();
          }
        })
    }



  },
  mounted() {
    this.queryAllSale();
    this.queryAllCustomer();
    this.queryAllJingLi();
  },
  created() {
    this.createSnowId();
    this.queryAllProduct();
  },
  watch: {
    'orderAppliaction.payment': {
      handler(newValue) {
        // 当付款方式为'0'(先发货后付款)时，禁用定金相关字段
        this.isDepositDisabled = newValue === '1';
        if (this.isDepositDisabled) {
          // 清空定金相关字段
          this.orderAppliaction.deposit = '';
          this.orderAppliaction.depositAmount = '';
        }
      },
      immediate: true
    },
    'orderAppliaction.orderType': {
      handler(newValue) {
        // 当订单种类为'0'(正常订单)时，禁用特价折扣字段
        this.isDiscountDisabled = newValue === '0';
        if (this.isDiscountDisabled) {
          // 清空特价折扣字段
          this.orderAppliaction.discount = '';
        }
      },
      immediate: true
    }
  },

}
</script>

<style scoped>
.box-card {
  margin-bottom: 20px;
}

.info-section {
  margin: 10px;
}

.info-row {
  display: flex;
  justify-content: space-between;
  margin-bottom: 10px;
}

.info-item {
  flex-basis: calc(33% - 10px);
  /* 减去margin-left的间距 */
  margin: 0 5px;
  display: flex;
  justify-content: flex-start;
  align-items: center;
  /* 垂直对齐 */
}

.info-item span {
  margin-left: 10px;
  width: 180px;
  /* 确保宽度一致 */
}



.total-info {
  display: flex;
  justify-content: flex-end;
  align-items: center;
  margin-top: 10px;
  font-weight: bold;
}

.total-info div {
  margin-left: 20px;
}

.section-title {
  font-size: 18px;
  font-weight: bold;
  color: #ffffff;
  background-color: #13d941;
  display: inline-block;
  padding: 5px 10px;
  margin-bottom: 10px;
  border-radius: 4px;
}

.custom-card {
  background-color: #D3DCE6;
  /* 你想要设置的底色 */
}

.button-group {
  display: flex;
  justify-content: flex-end;
  margin-top: 20px;
}

.fixed-buttons-horizontal {
  position: fixed;
  bottom: 20px;
  /* 根据需要调整距离底部的距离 */
  right: 20px;
  /* 根据需要调整距离右侧的距离 */
  display: flex;
  align-items: center;
  justify-content: flex-end;
  /* background-color: #f5f5f5; 容器的背景颜色 */
  /* padding: 10px; /* 内边距 */
  /* border-radius: 5px; 边框圆角 */
  /* box-shadow: 0 2px 5px rgba(0,0,0,0.2); 阴影效果 */
  z-index: 1000;
  /* 确保按钮位于最上层 */
}

.confirm-dialog {
  padding: 20px;
  background-color: #f8f9fa;
  border-radius: 8px;
}

.confirm-item {
  margin-bottom: 15px;
  padding: 10px;
  background-color: #fff;
  border-radius: 4px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.05);
}

.label {
  display: inline-block;
  width: 120px;
  color: #606266;
  font-weight: bold;
}

.value {
  color: #303133;
  font-size: 16px;
}

.price {
  color: #f56c6c;
  font-weight: bold;
}

.dialog-footer {
  margin-top: 20px;
  text-align: right;
}
</style>